const express=require("express");
const r=express.Router();
const uploadFile=require("../util/uploadfile.js");

//使用uploadFile中间件
r.post("/upload",uploadFile,(req,res,next)=>{
    console.log(req.body);
    if(req.body.photo==''){
        res.send({code:404,msg:'图片上传失败！'});
        return;
    }
    //将req.body里的数据存储到数据库
    res.send({code:200,msg:'图片上传成功！'});
});

r.post("/upimg", (req, res, next) => {
    console.log(req.files); //文件上传请求信息
    console.log(req.query.uid);

    let username = "zzz"; //这里的name需要用户登录，存在session中，然后从session中取出来
    let tempPath = req.files[0].path; //找到临时路径
    // console.log('tempPath: ', tempPath);
    // let filename=req.files.myfile.originalFilename;
    let filename = req.files[0].originalname;
    let targetPath = "./views/imgStoreHouse/avatar/" + username + "/" + filename; //将文件放入上传上来的目标路径
    console.log('targetPath: ', targetPath);
    if (myfs.existsSync("./views/imgStoreHouse/avatar/" + username) == false) { //判断upload路径下是否存在该用户的文件夹
        myfs.mkdirSync("./views/imgStoreHouse/avatar/" + username); //没有的话，就创建一个文件夹
    }
    myfs.rename(tempPath, targetPath, function (err, data) {
        if (err == null) {
            res.send("upload succeed!");
        } else {
            throw err; //抛出错误
        }
    });
});
module.exports=r;
